package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.UsersScore;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class UsersScoreApiImpl implements UsersScoreApi{
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public UsersScore findUsersScore(ObjectId id,Long userId) {
        Criteria questionnaireId = Criteria.where("questionnaireId").is(id).and("userId").is(userId);
        Query query = Query.query(questionnaireId).with(Sort.by(Sort.Order.desc("created"))).limit(1);
        UsersScore usersScores = mongoTemplate.findOne(query, UsersScore.class);
        //if list==null 抛异常
        return usersScores;
    }

    @Override
    public Boolean save(UsersScore usersScore) {

        try {
            mongoTemplate.save(usersScore);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public UsersScore findById(ObjectId objectId) {
        Query query = Query.query(Criteria.where("id").is(objectId));

        UsersScore usersScore = mongoTemplate.findOne(query, UsersScore.class);
        return usersScore;
    }

    @Override
    public List<UsersScore> findByUserScore(Integer userScore) {

        Query query = Query.query(Criteria.where("userScore").is(userScore));
        List<UsersScore> usersScores = mongoTemplate.find(query, UsersScore.class);
        return usersScores;
    }

    @Override
    public List<UsersScore> findByuserId(Long userId) {

        Query query = Query.query(Criteria.where("userId").is(userId));
        List<UsersScore> usersScoreList = mongoTemplate.find(query, UsersScore.class);
        return usersScoreList;
    }

    @Override
    public UsersScore findOneByuserId(Long userId) {

        Query query = Query.query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Order.desc("created"))).limit(1);
        UsersScore one = mongoTemplate.findOne(query, UsersScore.class);
        return one;
    }
}
